package com.weiquan.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.weiquan.entity.CommunityComment;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 社区评论Mapper接口
 */
@Mapper
public interface CommunityCommentMapper extends BaseMapper<CommunityComment> {

    /**
     * 获取帖子的评论列表（包含用户信息）
     */
    @Select("SELECT c.*, u.nickname, u.avatar " +
            "FROM community_comments c " +
            "LEFT JOIN sys_user u ON c.user_id = u.id " +
            "WHERE c.post_id = #{postId} AND c.is_deleted = 0 AND c.audit_status = 1 " +
            "ORDER BY c.create_time ASC")
    List<CommunityComment> selectCommentsByPostId(@Param("postId") Long postId);

    /**
     * 获取评论的回复列表
     */
    @Select("SELECT c.*, u.nickname, u.avatar " +
            "FROM community_comments c " +
            "LEFT JOIN sys_user u ON c.user_id = u.id " +
            "WHERE c.parent_id = #{parentId} AND c.is_deleted = 0 AND c.audit_status = 1 " +
            "ORDER BY c.create_time ASC")
    List<CommunityComment> selectRepliesByParentId(@Param("parentId") Long parentId);

    /**
     * 增加点赞数
     */
    @Update("UPDATE community_comments SET like_count = like_count + 1 WHERE id = #{id}")
    int increaseLikeCount(@Param("id") Long id);

    /**
     * 减少点赞数
     */
    @Update("UPDATE community_comments SET like_count = like_count - 1 WHERE id = #{id} AND like_count > 0")
    int decreaseLikeCount(@Param("id") Long id);

    /**
     * 获取用户的评论列表
     */
    @Select("SELECT c.*, p.title as post_title " +
            "FROM community_comments c " +
            "LEFT JOIN community_posts p ON c.post_id = p.id " +
            "WHERE c.user_id = #{userId} AND c.is_deleted = 0 " +
            "ORDER BY c.create_time DESC")
    List<CommunityComment> selectByUserId(@Param("userId") Long userId);

    /**
     * 统计帖子评论数
     */
    @Select("SELECT COUNT(*) FROM community_comments " +
            "WHERE post_id = #{postId} AND is_deleted = 0 AND audit_status = 1")
    int countByPostId(@Param("postId") Long postId);
}